package com.mbigger.admin.dao;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.mbigger.admin.beans.PageQuery;
import com.mbigger.admin.entity.User;
/**
 * 用户
 * @author mbigg
 *
 */
@Mapper
public interface UserMapper {
	
	@Delete("DELETE FROM sys_user where id=#{id}")
	int deleteById(@Param("id")Integer id);
	
	@Insert("INSERT INTO sys_user (username, telephone, mail, password, dept_id, status, remark, operator, operate_time, operate_ip) "
			+ "VALUES (#{username}, #{telephone}, #{mail}, #{password}, #{deptId}, #{status}, #{remark}, #{operator}, #{operateTime}, #{operateIp})")
	@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
	int insert(@Param("user")User user);
	
	@Select("SELECT * FROM sys_user WHERE id=#{id}")
	User selectById(@Param("id")Integer id);
	
	@Update("UPDATE sys_user SET username=#{username}, telephone=#{telephone}, mail=#{mail}, dept_id=#{deptId}, status=#{status},remark=#{remark}, operator=#{operator}, operate_time=#{operateTime}, operate_ip=#{operateIp} WHERE id=#{id}")
	int updateById(User user);

	@Select("SELECT * FROM sys_user WHERE telephone=#{keyword} OR mail=#{keyword} OR username=#{keyword}")
	User findByKeyword(@Param("keyword")String keyword);
	
	@Select("<script>"
			+ "SELECT count(1) FROM sys_user WHERE mail=#{mail} "
			+ "<if test='id != null'>"
			+ "AND id!=#{id}"
			+ "</if>"
			+ "</script>")
	int countByMail(@Param("mail")String mail, @Param("id")Integer id);
	
	@Select("<script>"
			+ "SELECT count(1) FROM sys_user WHERE telephone=#{telephone} "
			+ "<if test='id != null'>"
			+ "AND id!=#{id}"
			+ "</if>"
			+ "</script>")
	int countByTelephone(@Param("telephone")String telephone, @Param("id")Integer id);
	
	@Select("SELECT count(1) FROM sys_user WHERE dept_id=#{deptId}")
	int countByDeptId(@Param("deptId") int deptId);
	
	@Select("SELECT * FROM sys_user WHERE dept_id=#{deptId} ORDER BY username ASC LIMIT #{page.offset}, #{page.pageSize}")
	List<User> getPageByDeptId(@Param("deptId")int deptId, @Param("page")PageQuery page);
	
	@Select("<script>"
			+ "SELECT * FROM sys_user WHERE id IN "
			+ "<foreach collection='idList' item='id' open='(' close=')' separator=','>"
			+ "#{id}"
			+ "</foreach>"
			+ "</script>")
	List<User> getByIdList(@Param("idList")List<Integer> idList);
	
	@Select("SELECT * FROM sys_user")
	List<User> getAll();
}
